package view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import model.VoteResult;

public class ViewResultsPanel extends JPanel implements ActionListener {

	private ClientFrame frame;
	private JLabel resultsLabel;
	private JButton backButton;
	private JTextArea resultArea;
	private JScrollPane scrollingArea;
	private List<VoteResult> resultsList;

	@SuppressWarnings("unchecked")
	public ViewResultsPanel(ClientFrame f) {
		frame = f;
		this.setBounds(0, 0, frame.getWidth(), frame.getHeight());
		this.setBackground(Color.WHITE);
		this.setLayout(null);

		resultsLabel = new JLabel("Votting results: ");
		resultsLabel.setBounds(300, 150, 100, 20);
		this.add(resultsLabel);

		try {
			Socket connectionSocket = new Socket("127.0.0.1", 4444);
			ObjectOutputStream objectOut = new ObjectOutputStream(
					connectionSocket.getOutputStream());
			ObjectInputStream objectIn = new ObjectInputStream(connectionSocket
					.getInputStream());

			objectOut.writeObject("get results");
			objectOut.flush();
			resultsList = (List<VoteResult>) objectIn.readObject();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		String voteResults = "";
		int x = 1;
		for (VoteResult voteResult : resultsList) {
			voteResults += x + ") " + voteResult.getCandidateName()
					+ "      \t" + voteResult.getNumberOfVotes() + " votes\n";
			x++;
		}

		resultArea = new JTextArea();
		resultArea.setText(voteResults);
		resultArea.setEditable(false);
		resultArea.setWrapStyleWord(true);
		scrollingArea = new JScrollPane(resultArea);
		scrollingArea.setBounds(300, 180, 300, 200);
		this.add(scrollingArea);

		backButton = new JButton("Back");
		backButton.setBounds(300, 390, 90, 20);
		backButton.addActionListener(this);
		// this.add(backButton);

		this.repaint();

		frame.setContentPane(this);

	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == backButton) {

		}

	}
}
